package Tree;

import java.util.LinkedList;
import java.util.List;

public class p102二叉树的层序遍历 {
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            LinkedList<TreeNode> queue = new LinkedList<>();
            List<List<Integer>> list = new LinkedList<>();
            if (root == null) {
                return list;
            }
            queue.add(root);
            while (!queue.isEmpty()) {
                // 获取当前队列中的根结点数 len 用于遍历寻找各自的孩子结点
                int len = queue.size();
                LinkedList<Integer> itemList = new LinkedList<>();

                while (len > 0) {
                    TreeNode node = queue.poll();
                    itemList.add(node.val);
                    if (node.left != null) queue.add(node.left);
                    if (node.right != null) queue.add(node.right);

                    len--;
                }

                list.add(itemList);

            }
            return list;
        }
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
